# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
import simplejson
import glob
import os.path

deck_seed_map = {}
data_fn = './data/small-list'
data_fh = None
MAX_SEED=32000

def read_deck_from_file(seed):
    assert (seed >= 0 and seed <= MAX_SEED)
    assert data_fh
    data_fh.seek(seed*52)
    s = data_fh.read(52)
    deck = [ord(i) for i in s]
    assert len(deck) == 52
    return deck


def index(request):
    return render_to_response('./freecell/index.html')

def get_deck_by_seed(request):
    print 'here'
    seed = request.REQUEST["seed"]
    print type(seed)
    seed = int(seed)
    assert (seed >= 0 and seed <= MAX_SEED)
    global data_fh, deck_seed_map
    if data_fh is None:
        #first time 
        data_fh = open(data_fn, 'r')
    deck = []
    if deck_seed_map.has_key(seed):
        print 'already have such deck'
        deck = deck_seed_map[seed]
    else:
        print 'read it from file'
        deck = read_deck_from_file(seed)
        deck_seed_map[seed] = deck
    print deck
    return HttpResponse(simplejson.dumps({'deck': deck}))


def show_cards(request):
    files = glob.glob('./media/card*.gif');
    files = [ '/site_media/%s' % os.path.basename(file) for file in files]
    unit_per_line = 10
    max_row = len(files) / unit_per_line;
    data = []
    for row in range(max_row):
        unit = unit_per_line
        if row == max_row-1:
            unit = len(files) % unit_per_line
        line = []
        for u in range(unit):
            line.append( files[row*unit_per_line+u] )
        data.append(line)
    return render_to_response('./freecell/showcards.html', { 'data' : data } )
    

